package model

import (
	"fmt"
	"gorm.io/gorm/clause"
	"server/common"
)

type ToolMeau struct {
	Model
	Name   string `gorm:"comuln:name;not null" json:"name"`
	Father uint   `gorm:"comuln:father;not null;default:0" json:"father"`

	//ToolMeauID int        `gorm:"comuln:tool_meau_id;" json:"tool_meau_id"`
	//Childs     []ToolMeau `gorm:"-" json:"childs"`

	OwnerID int `json:"owner_id" json:"owner_id"`
	Owner   Owner

	Tools []Tool `gorm:"-" json:"tools"`
}

func (tr *ToolMeau) TableName() string {
	return "tool_meau"
}

func (tr *ToolMeau) Create() error {
	if result := common.DB.Omit(clause.Associations).Create(&tr); result.Error != nil {
		return result.Error
	}
	fmt.Println(tr)
	return nil
}

func (tr *ToolMeau) List(father int) []ToolMeau {
	var tools_list []ToolMeau
	if err := common.DB.Debug().Model(&ToolMeau{}).Preload(clause.Associations).Where("father = ?", father).Find(&tools_list).Error; err != nil {
		return tools_list
	}
	return tools_list
}

func (tr *ToolMeau) Update() error {
	if err := common.DB.Where("name = ?", tr.Name).Updates(&tr).Error; err != nil {
		return err
	}
	return nil
}

func (tr *ToolMeau) Delete() error {
	if err := common.DB.Where("name = ?", tr.Name).Delete(&tr).Error; err != nil {
		return err
	}
	return nil
}
